package com.jasiri.project.adapter

import android.graphics.Typeface
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.jasiri.project.R
import com.jasiri.project.utils.LanguageUtils
import com.jasiri.project.utils.config.Configs
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.http.HttpHelper
import com.jasiri.project.weight.font.NormalEditText
import com.jasiri.lib.baseadapter.JasiriRecyclerViewAdapter
import com.jasiri.lib.baseadapter.JasiriViewHolderHelper
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/18 10:43
 * @Annotation：流程常规通用适配器
 */
class ProcessCommonAdapter(recyclerView: RecyclerView?) : JasiriRecyclerViewAdapter<JSONObject>(recyclerView) {

    //是否是通用样式，通用样式 tvTitle为加粗字体，非通用样式为默认字体
    var typeFaceStyle = Typeface.BOLD

    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK" ->{//时间选择
                return R.layout.item_process_common_select
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                return R.layout.item_process_contact_relation_select
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.item_process_common_mobile
            }
            "SELECT" -> {//选择
                return R.layout.item_process_common_select
            }
            else -> {//输入框
                return R.layout.item_process_common_input
            }
        }
    }

    override fun setItemChildListener(helper: JasiriViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.selectLayout)//选择
        helper.setItemChildClickListener(R.id.imgMobileBook)//选择联系人
        helper.setItemChildClickListener(R.id.tvMobile)
    }

    override fun fillData(helper: JasiriViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val tvTitle = helper.getTextView(R.id.tvTitle)
        var showTitle = model.optString("title")
        if (LanguageUtils.isSwahili()){
            showTitle = model.optString("title_sw")
        }

        tvTitle.text = findKeywordColor(ContextCompat.getColor(mContext,R.color.FFFF4D3E),showTitle,"*")
        tvTitle.setTypeface(Typeface.DEFAULT,typeFaceStyle)

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                showSelectView(helper,position,model)
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                showContactRelationView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showContactMobileView(helper,position,model)
            }
            else -> {//输入框
                showInputView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showInputView(helper: JasiriViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var hint = model.optString("hint")
        if (LanguageUtils.isSwahili()){
            hint = model.optString("hint_sw")
        }

        val editText = helper.getView<NormalEditText>(R.id.editText)
        editText.setHint(hint)
        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            if (selectItem != null) {
                showText = selectItem.optString("title")
            }
        }
        editText.setText(showText)
        editText.setInputFocusChangeListener(object : NormalEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String) {
                val eventType = String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName"))
                HttpHelper.addEvent(eventType,remark)
            }
        })

        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }
        editText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择类型
     */
    private fun showSelectView(helper: JasiriViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var hint = model.optString("hint")
        if (LanguageUtils.isSwahili()){
            hint = model.optString("hint_sw")
        }

        val tvValue = helper.getTextView(R.id.tvValue)
        tvValue.setHint(hint)
        if (model.has("selectItem")){

            val selectItem = model.getJSONObject("selectItem")
            var showTitle = selectItem.optString("title")
            if (LanguageUtils.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            tvValue.text = showTitle
        }
    }

    /**
     * 联系人关系
     */
    private fun showContactRelationView(helper: JasiriViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (LanguageUtils.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        //选择关系
        val tvValue = helper.getTextView(R.id.tvValue)
        tvValue.setHint(showHint)
        //输入关系
        val editText = helper.getView<NormalEditText>(R.id.editText)
        //todo 此处确实选择Other时输入框的提示
        editText.setHint(model.optString("relationOtherHint"))
        editText.visibility = View.GONE

        var showTitle = ""
        var showOtherValue = ""
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            showTitle = selectItem.optString("title")
            if (LanguageUtils.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }

            if (showTitle == model.optString("relationOtherKey")){
                editText.visibility = View.VISIBLE
                if (selectItem.has("otherValue")){
                    showOtherValue = selectItem.optString("otherValue","")
                }
            }
        }
        tvValue.text = showTitle

        //关系为“Other”时，输入框允许输入
        editText.isEnabled = showTitle == model.optString("relationOtherKey")
        editText.setText(showOtherValue)
        editText.setInputFocusChangeListener(object : NormalEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(EventType.FORM.FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addEvent(eventType,remark)
            }
        })
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }

        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (model.has("selectItem")){
                    val selectItem = model.getJSONObject("selectItem")
                    selectItem.put("otherValue",s.toString())
                }
            }
        })
    }

    /**
     * 联系电话
     */
    private fun showContactMobileView(helper: JasiriViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var hint = model.optString("hint")
        if (LanguageUtils.isSwahili()){
            hint = model.optString("hint_sw")
        }

        val textMobile = helper.getTextView(R.id.tvMobile)
        textMobile.setHint(hint)
        val editMobile = helper.getView<EditText>(R.id.editMobile)
        editMobile.setHint(hint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            textMobile.text = showValue
            editMobile.setText(showValue)
        }
        editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editMobile.clearFocus()
                true
            }
            false
        }
        editMobile.setOnFocusChangeListener { v, hasFocus ->
            if (!hasFocus){
                HttpHelper.addEvent(String.format(EventType.FORM.FORM_STEP_INPUT_XX,model.optString("paramName")),editMobile.text.toString())
            }
        }
        editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
        //设备是否支持通讯录选择联系人
        if (model.optBoolean("isContactPick")){
            helper.setVisibility(R.id.imgMobileBook,View.VISIBLE)
            //是否是审核账号
            val isConfigAccount = Configs.getSPBoolean(Configs.SPKEY.JASIRI_IS_CONFIG_ACCOUNT)
            if(isConfigAccount){//审核账号 - 允许输入或选择
                textMobile.visibility = View.GONE
                editMobile.visibility = View.VISIBLE
            } else {//非审核账号只能选择
                textMobile.visibility = View.VISIBLE
                editMobile.visibility = View.GONE
            }
        } else {//不支持通讯录选择
            helper.setVisibility(R.id.imgMobileBook,View.INVISIBLE)
            textMobile.visibility = View.GONE
            editMobile.visibility = View.VISIBLE
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}